#!/usr/bin/python
# coding: utf-8

import argparse
import os

from apitest.__version__ import __version__
from apitest.cmd.output import out_dir_path
from apitest.engine.const.enums import GenType

parser = argparse.ArgumentParser(description="网电平台接口自动化框架")
parser.add_argument('-g', '--gen', nargs='?', choices=['init', 'http', 'rpc', 'idl', 'db'], type=str,
                    help='工具生成类型：api: 根据IDL文件生成项目api code；demo：生成项目demo；idl：更新本地IDL文件'
                    )
parser.add_argument('-v', '--version', action="store_true", help='')
parser.add_argument('-p', '--psm', nargs='?', type=str,
                    help='Service psm name. eg: motor.trade.online_sales'
                    )
parser.add_argument('-i', '--idl', nargs='?', type=str,
                    help='The relative path to the idl file. eg: idls/motor/http_idl/trade/trade_online_sales.thrift'
                    )
parser.add_argument('-b', '--branch', nargs='?', type=str, default="master",
                    help='code branch. eg: master'
                    )
parser.add_argument('-d', '--dbname', nargs='?', type=str, help='Please input dbname, eg:  "motor_trade')
parser.add_argument('-t', '--type', choices=['regex', 'keywords', 'tables'], type=str,
                    help='Filter rule type. eg: regex'
                    )
parser.add_argument('-c', '--code', nargs='?', type=str, help='Filtering rules. eg:  "wd_')
parser.add_argument('-o', '--out', nargs='?', type=str, help='Output directory. eg: ./idls')
parser.add_argument('-n', '--new', nargs='?', type=str, default="true", help='是否使用新版本')

args = parser.parse_args()


def main():
    repo_path = os.getcwd()

    if args.version:
        print("apitest version is %s.\n" % str(__version__))

    elif args.gen:
        gen_type = GenType(args.gen)

        if gen_type is GenType.init:
            from apitest.cmd.generate_project import GenProjectInit
            print("开始初始化项目。。。")
            GenProjectInit.generate_demo_zip()
            print("项目生成完成")

        elif gen_type is GenType.idl:
            from apitest.cmd.download_idl import DownloadIdl
            DownloadIdl(repo_path, args.psm, args.branch, args.out).request_related_thrift_files()

        elif gen_type is GenType.http:
            from apitest.cmd.generate_api import GenHttpCode
            print("\n开始解析idl文件...")
            print("输入psm为：", args.psm)
            if os.path.exists(args.idl):
                idl = args.idl
            else:
                idl = os.path.join(repo_path, args.idl)
            print("idl文件为：", idl)
            out_dir = out_dir_path(repo_path, psm=args.psm)
            print("api存放路径为：", out_dir)
            is_new = True
            if args.new == 'false':
                is_new = False
            gen_http = GenHttpCode(args.psm, idl, out_dir, is_new=is_new)
            gen_http.generate_init(gen_type)
            gen_http.generate_http_client()
            print("client.py生成完成！")
            gen_http.generate_http_route()
            print("route.py生成完成！")
            gen_http.generate_https_model()
            print("model.py生成完成！")
            gen_http.clear()

        elif gen_type is GenType.rpc:
            from apitest.cmd.generate_rpc import GenRPCCode
            print("\n开始解析idl文件...")
            print("输入psm为：", args.psm)
            if os.path.exists(args.idl):
                idl = args.idl
            else:
                idl = os.path.join(repo_path, args.idl)
            print("idl文件为：", idl)

            out_dir = out_dir_path(repo_path, psm=args.psm)
            gen_rpc = GenRPCCode(args.psm, idl, out_dir)
            gen_rpc.generate_init(gen_type)
            gen_rpc.generate_rpc_client()
            print("client.py生成完成！")
            gen_rpc.generate_rpc_model()
            print("model.py生成完成！")
            gen_rpc.clear()

        elif gen_type is GenType.db:
            from apitest.cmd.generate_mysql import GenMysqlModel
            from apitest.engine.const.model import FilterRule
            filter_rule = None
            if args.type and args.code:
                if args.code.startswith("[") and args.code.endswith("]"):
                    code = eval(args.code)
                else:
                    code = str(args.code)
                filter_rule = FilterRule(rule_type=args.type, rule_code=code)
            gmm = GenMysqlModel(name=args.dbname, out=args.out, filter_rule=filter_rule)
            gmm.genMysqlModel()
